import logging

import requests

from Util.DBUtil import DBUtil
from sqlalchemy import text

from cdp_error_service.ApiExecutionLogDB import ApiExecutionLogDB
from cdp_error_service.api_get_token_2 import get_upm_token_server

#手工执行标签接口
tag_service_url = 'https://www.cdp.changan.com.cn/tag-system/api/mergeobject/tag/{}/execute'

querySql = (
    "SELECT tag_id as id FROM( SELECT tag_id, FORMAT( abs(( t.now_cover_count - t.yest_cover_count)/ t.yest_cover_count * 100 ), 2 ) AS coverage_varies FROM ( SELECT t1.tag_id, t1.cover_count AS now_cover_count, t2.cover_count AS yest_cover_count "
    " FROM ( SELECT tag_id, cover_count FROM object_modeling_v2.om_tag_exec WHERE id IN ( SELECT max(id) id FROM object_modeling_v2.om_tag_exec ote WHERE DATE (created_dt)= DATE ( now()) GROUP BY tag_id ) AND exec_status = 300 ) t1 "
    " INNER JOIN ( SELECT tag_id, cover_count FROM object_modeling_v2.om_tag_exec WHERE id IN ( SELECT max(id) id FROM object_modeling_v2.om_tag_exec ote WHERE DATE (created_dt) != DATE ( now()) GROUP BY tag_id ) AND exec_status = 300 ) t2 ON t1.tag_id = t2.tag_id ) t ) t WHERE t.coverage_varies > 35 ")


class TagService:
    def __init__(self, db_url):
        self.db_url = db_url
        self.api_log_db = ApiExecutionLogDB()

    def tag_error_list(self):
        db_self = DBUtil(self.db_url)
        logging.info(querySql)
        results = db_self.execute_query(text(querySql))
        url_list = []  # 创建一个空列表来存储替换后的URL
        if results:
            for row in results:
                tag_id = row[0]  # 获取第一个元素，即 id 列的值
                url = tag_service_url.format(tag_id)  # 使用 format() 方法将 tag_id 插入到 URL 中
                url_list.append(url)  # 将替换后的 URL 添加到列表中
                logging.info(f"Tag ID: {tag_id}, URL: {url}")
        return url_list  # 返回包含所有替换后的 URL 的列表

    def tag_execute(self, urls):
        if not urls:
            logging.info("URL list is empty")
            return
        upm_token_server = get_upm_token_server()
        upm_token = upm_token_server.get_redis_token()
        if not upm_token:
            print("token获取失败")
        else:
            head_map = upm_token.get_head_map()
            cookie_map = upm_token.get_cookie_map()
            for url in urls:
                response = requests.put(url, headers=head_map, cookies=cookie_map, json={})
                self.api_log_db.insert_log("tag_execute", url, response.text, response.status_code, "")
                print(f"HTTP Response: {response.status_code} {response.text}")




# 运行主函数
if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO)
    tag_service = TagService(
        "mysql+pymysql://root:d1o0N1z!rbELRf3r@rm-2vc9b10eck3rpbbv7.mysql.cn-chengdu.rds.aliyuncs.com:3306/object_modeling_v2")
    urls = tag_service.tag_error_list()
    logging.info(f"All URLs: {urls}")
    tag_service.tag_execute(urls)
